import { useEffect, useState } from "react";
import { connect } from 'react-redux';
import { useLocation, Navigate } from "react-router-dom";
import { AxiosCanceler } from "@/api/helper/axiosCancel";
import { searchRoute } from "@/utils/util";
import { rootRouter, filterData } from "@/routers/index";
import { HOME_URL } from "@/config/config";
import { store } from "@/redux/index";
import { setAuthButtons, setAuthRouter } from "@/redux/modules/auth/action";
import { updateCollapse } from "@/redux/modules/menu/action";
import { setUserInfo } from '@/redux/modules/global/action';
import { getBindInfo, getUserInfo } from "@/api/modules/login";

const axiosCanceler = new AxiosCanceler();

/**
 * @description 路由守卫组件
 * */
const AuthRouter = (props: any) => {
	const [loading, setLoading] = useState(false);
	const { pathname } = useLocation();
	const route = searchRoute(pathname, rootRouter);
	const getUserInfoFunc = async () => {
		try {
			setLoading(true);
			const [info1, info2]: any = await Promise.all([getUserInfo(), getBindInfo()]);
			const { permission, supplier, supplier_user } = (info1.data || {});
			const authMenuKey = (permission || {}).menu || [];
			const authBtnsKey = (permission || {}).btn || [];
			props.setUserInfo({
				bindInfo: info2.data,
				permission,
				supplier,
				supplier_user,
				...(supplier_user || {})
			});
			props.setAuthRouter(authMenuKey);
			props.setAuthButtons(authBtnsKey);
			setTimeout(() => setLoading(false), 16.6666);
		} catch (err) {
			setLoading(false);
		}
	};

	useEffect(() => {
		getUserInfoFunc();
	}, []);

	// * 在跳转路由之前，清除所有的请求
	axiosCanceler.removeAllPending();
	// * Dynamic Router(动态路由，根据后端返回的菜单数据生成的一维数组)
	const dynamicRouter = store.getState().auth.authRouter;

	if (loading) return '';
	
	// * 判断当前路由是否需要访问权限(不需要权限直接放行)
	if (!route.meta?.requiresAuth) return props.children;

	// * 判断是否有Token
	if (!store.getState().global.token) return <Navigate to="/login" replace />;

	// * Static Router(静态路由，必须配置首页地址，否则不能进首页获取菜单、按钮权限等数据)，获取数据的时候会loading，所有配置首页地址也没问题
	const staticRouter = [HOME_URL, "/403"];
	const routerList = filterData(dynamicRouter)[1].concat(staticRouter);
	// * 如果访问的地址没有在路由表中重定向到403页面

	if (routerList.indexOf(pathname) == -1) return <Navigate to="/403" />;

	// * 当前账号有权限返回 Router，正常访问页面
	return props.children;
};

const mapStateToProps = (state: any) => state.auth;
const mapDispatchToProps = { setAuthButtons, updateCollapse, setAuthRouter, setUserInfo };
export default connect(mapStateToProps, mapDispatchToProps)(AuthRouter);
